package com.bdqn.qnnews.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.qnnews.common.base.PageResult;
import com.bdqn.qnnews.common.base.ResultCode;
import com.bdqn.qnnews.common.utils.ThreadLocalUtils;
import com.bdqn.qnnews.minio.utils.MinioUtil;
import com.bdqn.qnnews.rest.exception.ApplicationException;
import com.bdqn.qnnews.wemedia.entity.WmMaterial;
import com.bdqn.qnnews.wemedia.mapper.WmMaterialMapper;
import com.bdqn.qnnews.wemedia.service.WmMaterialService;
import com.bdqn.qnnews.wemedia.vo.MaterialVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author xlz
 * @since 2023-12-26
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    private final MinioUtil minioUtil;

    @Override
    public WmMaterial uploadPicture(MultipartFile multipartFile) {
        // 1. 将图片保存到minio
        // 1.1 校验参数
        if(multipartFile.isEmpty()){
            throw new ApplicationException(ResultCode.PARAM_INVALID);
        }
        // 1.2 判断是否登录（获取登录用户信息）
        Long userId = null;
        try {
            userId = Long.parseLong((String) ThreadLocalUtils.get());
        } catch (NumberFormatException e) {
            log.debug("--用户数据解析异常：{}",e.getMessage());
            throw new ApplicationException(ResultCode.NEED_LOGIN);
        }
        try {
            // 1.3 上传图片到minio
            // 处理图片名称，去重
            final String uuidStr = UUID.randomUUID().toString().replaceAll("-", "");
            String filename = multipartFile.getOriginalFilename();
            // 断言，相当于if条件
            assert filename != null;
            final String fileSuffix = filename.substring(filename.lastIndexOf('.'));
            // 拼接文件名称
            filename = uuidStr + System.currentTimeMillis() + fileSuffix;
            // 上传图片
            final String imgUrl = minioUtil.uploadImgFile("", filename, multipartFile.getInputStream());

            // 创建是一个素材实体类对象
            final WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(userId);
            wmMaterial.setUrl(imgUrl);
            wmMaterial.setType((byte) 0);
            wmMaterial.setCreatedTime(LocalDateTime.now());
            wmMaterial.setCollection(false);

            // 将数据保存打mysql数据库中
            save(wmMaterial);

            //返回素材信息
            return wmMaterial;
        } catch (IOException e) {
            e.printStackTrace();
            throw new ApplicationException("图片上传minio异常");
        }
    }

    @Override
    public PageResult<List<WmMaterial>> findList(MaterialVo vo) {
        //判断是否登录（获取登录用户信息）
        String userId = (String)ThreadLocalUtils.get();
        if(userId==null){
            throw new ApplicationException(ResultCode.NEED_LOGIN);
        }
        //准备分页参数
        IPage<WmMaterial> iPage = new Page<>(vo.getPage(),vo.getSize());

        //准备条件参数
        QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
        //判断当前登录用户
        queryWrapper.eq("user_id",userId);

        //是否收藏
        if(vo.getIsCollection() != null && vo.getIsCollection() == 1){
            // 如果查询的收藏图片，才添加查询条件
            queryWrapper.eq("is_collection",vo.getIsCollection());
        }

        //排序  降序，将新添加的素材显示在前面
        queryWrapper.orderByDesc("created_time");

        // 分页查询
        final IPage<WmMaterial> pageData = page(iPage, queryWrapper);

        // 将数据封装为统一的分页响应对象
        return new PageResult<List<WmMaterial>>()
                .setData(pageData.getRecords())
                .setCurrentPage(vo.getPage())
                .setTotal((int) pageData.getTotal())
                .setSize((int) pageData.getSize());
    }

    @Override
    public boolean removeMaterial(Long mId) {
        // 先查询当前的素材信息，获取素材的url
        final WmMaterial wmMaterial = getById(mId);
        if (wmMaterial == null){
            throw new ApplicationException("删除的素材id异常");
        }
        // 根据url删除minio上的素材
        try {
            minioUtil.delete(wmMaterial.getUrl());
            // 删除mysql数据库中的
            return removeById(mId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApplicationException(e.getMessage());
        }
    }
}
